package com.hustzp.com.xichuangzhu.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.hustzp.com.xichuangzhu.R;
import com.hustzp.com.xichuangzhu.SharedParametersService;
import com.hustzp.com.xichuangzhu.XichuangzhuApplication;
import com.hustzp.com.xichuangzhu.dao.ReViewDao;
import com.hustzp.com.xichuangzhu.fragment.ReViewFragment;
import com.hustzp.com.xichuangzhu.model.Review;
import com.hustzp.com.xichuangzhu.poetry.PoetryDetailAct;
import com.hustzp.com.xichuangzhu.poetry.model.Works;
import com.hustzp.com.xichuangzhu.utils.ScreenUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by vonchenchen on 2015/10/28 0028.
 */
public class FlyBackground extends RelativeLayout implements XichuangzhuApplication.TextTypefaceChangeListener, XichuangzhuApplication.TrChangeListener {

    private Context context;
    private ScaleRelativeLayout topScaleRelativeLayout;
    private ScaleRelativeLayout midScaleRelativeLayout;
    private ScaleRelativeLayout rltScaleRelativeLayoutBg;
    //显示列表
    private List<Review> showList;
    //已经显示列表
    private List<String> noShowList;
    //    private HorizontalScrollView horizontalScrollViewMidle;
    private LinearLayout llMidle;

    //    private HorizontalScrollView horizontalScrollViewTop;
    private LinearLayout llTop;
    private FontTextView tvTopAuthor;
    private FontTextView tvMiddleAuthor;
    private Review reViewQuotes;
    private Review topView = null;
    private OnLoadColection onLoadColection;

    public OnLoadColection getOnLoadColection() {
        return onLoadColection;
    }

    public void setOnLoadColection(OnLoadColection onLoadColection) {
        this.onLoadColection = onLoadColection;
    }

    public interface OnLoadColection {
        void loadCollection(Review review);
    }

    public Review getTopReview() {
        return topView;
    }

    public ScaleRelativeLayout getTopView() {
        return topScaleRelativeLayout;
    }

    public Review getReViewQuotes() {
        return reViewQuotes;
    }

    public void setReViewQuotes(Review reViewQuotes) {
        this.reViewQuotes = reViewQuotes;
        showList.clear();
        showList.add(reViewQuotes);
        showList.add(reViewQuotes);
        topScaleRelativeLayout.setCanFlip(false);
        midScaleRelativeLayout.setCanFlip(false);
        showData();
    }

    //存两张
    public FlyBackground(Context context) {
        super(context);
        this.context = context;
        XichuangzhuApplication.getInstance().setTextTypefaceChangeListener(this);
        XichuangzhuApplication.getInstance().setTrChangeListener(this);
        initData();
    }

    public FlyBackground(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        XichuangzhuApplication.getInstance().setTextTypefaceChangeListener(this);
        XichuangzhuApplication.getInstance().setTrChangeListener(this);
        initData();
    }

    private void initData() {

        ReViewDao reViewDao = new ReViewDao(this.context);
        Review review = new Review();
        review.setAuthor_id(10025);
        review.setWygtfs_error("1");
        String localHostory = SharedParametersService.getHistoryQuote(context);
        noShowList = new ArrayList<>();
        if (!TextUtils.isEmpty(localHostory)) {
            String[] s = localHostory.split(",");
            if (s.length > 0) {
                for (String id : s) {
                    if (!TextUtils.isEmpty(id)) {
                        noShowList.add(id);
                    }
                }
            }
        }
        //默认初始化显示两条
        showList = reViewDao.getByReview(review, localHostory, 2l);
        addNoShowCache(showList);
    }

    public void setTopView(Review topView) {
        this.topView = topView;
    }

    private void showData() {

        topView = showList.get(0);
        setTopView(topView);
        topScaleRelativeLayout.setTag(topView);

        Review middleView = showList.get(1);

        String midle = "";
        String top = "";
        String midleAuthor = "";
        String topAuthor = "";

        // 1 简体 2 繁体
        if ("1".equals(XichuangzhuApplication.getInstance().getFanjian())) {

            midle = middleView.getQuote();
            top = topView.getQuote();

            midleAuthor = middleView.getAuthor();
            topAuthor = topView.getAuthor();

        } else {
            midle = middleView.getQuote_tr();
            top = topView.getQuote_tr();

            midleAuthor = middleView.getAuthor_tr();
            topAuthor = topView.getAuthor_tr();
        }

        String[] tops = top.split("[，。：；？！、]");
        String[] middles = midle.split("[，。：；？！、]");
        llTop.removeAllViews();
        llMidle.removeAllViews();
        LayoutInflater inflater = LayoutInflater.from(context);
        for (int i = tops.length - 1; i >= 0; i--) {
            View v = inflater.inflate(R.layout.frag_review_body_item, null);
            FontTextView textView = (FontTextView) v.findViewById(R.id.tv_content);
            textView.setTypeface();
            textView.setText(tops[i]);
            llTop.addView(v);
        }
        for (int i = middles.length - 1; i >= 0; i--) {
            View v = inflater.inflate(R.layout.frag_review_body_item, null);
            FontTextView textView = (FontTextView) v.findViewById(R.id.tv_content);
            textView.setTypeface();
            textView.setText(middles[i]);
            llMidle.addView(v);
        }
        tvTopAuthor.setTypeface();
        tvMiddleAuthor.setTypeface();
        tvTopAuthor.setText(topAuthor);
        tvMiddleAuthor.setText(midleAuthor);
        if (getOnLoadColection() != null) {
            getOnLoadColection().loadCollection(topView);
        }
        //加载新数据
        loadNewData();
    }

    public void addNoShowCache(List<Review> reviews) {
        for (Review newView : reviews) {
            noShowList.add(newView.getId() + "");
            if (noShowList.size() > 10) {
                noShowList.remove(0);
            }
        }
    }

    private void loadNewData() {
        ReViewDao reViewDao = new ReViewDao(this.context);
        Review review = new Review();
        review.setAuthor_id(10025);
        review.setWygtfs_error("1");
        String localHostory = listToString(noShowList);
//        Log.e("wzm", localHostory);
        SharedParametersService.saveHistoryQuote(context, localHostory);
        //最后一条数据为缓存数据,还没显示,也未增加到缓存,但是下次查询不能包含这条数据
        if (showList.size() > 0) {
            localHostory += "," + showList.get(showList.size() - 1).getId();
        }
        List<Review> newList = reViewDao.getByReview(review, localHostory, 1l);
        //新查询到的数据填充到不显示列表,避免数据出现重复
        showList.addAll(newList);
    }

    /**
     * @Description:把list转换为一个用逗号分隔的字符串
     */
    public static String listToString(List list) {
        StringBuilder sb = new StringBuilder();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (i < list.size() - 1) {
                    sb.append(list.get(i) + ",");
                } else {
                    sb.append(list.get(i));
                }
            }
        }
        return sb.toString();
    }

    private void initView() {

        topScaleRelativeLayout = (ScaleRelativeLayout) this.findViewById(R.id.rlytTopScaleRelativeLayout);
        topScaleRelativeLayout.setIsTop(true);

//        horizontalScrollViewMidle = (HorizontalScrollView) this.findViewById(R.id.horizontalScrollViewMidle);
        llMidle = (LinearLayout) this.findViewById(R.id.ll_middleLayout);
//        textViewVerticalMidle.setHandler(handler);

//        horizontalScrollViewTop = (HorizontalScrollView) this.findViewById(R.id.horizontalScrollViewTop);
        llTop = (LinearLayout) this.findViewById(R.id.ll_topLayout);
//        textViewVerticalTop.setHandler(handler);

        midScaleRelativeLayout = (ScaleRelativeLayout) this.findViewById(R.id.rlytMinScaleRelativeLayout);
        midScaleRelativeLayout.setIsTop(false);
        rltScaleRelativeLayoutBg = (ScaleRelativeLayout) this.findViewById(R.id.rltScaleRelativeLayoutBg);
        LayoutParams params = (LayoutParams) topScaleRelativeLayout.getLayoutParams();
        params.width = ScreenUtils.getScreenWidth(context) - ScreenUtils.dip2px(context, 64*1.5f);
        params.height = ScreenUtils.getScreenHeight(context) - ScreenUtils.dip2px(context, 95*1.5f) - ScreenUtils.dip2px(context, 50);
        topScaleRelativeLayout.setLayoutParams(params);
        midScaleRelativeLayout.setLayoutParams(params);
        rltScaleRelativeLayoutBg.setLayoutParams(params);
        tvTopAuthor = (FontTextView) this.findViewById(R.id.tv_top_author);
        tvMiddleAuthor = (FontTextView) this.findViewById(R.id.tv_middle_author);
    }

    private void initListener() {

        topScaleRelativeLayout.setOnDismissListener(new ScaleRelativeLayout.OnDismissListener() {
            @Override
            public void onLeftDismiss(View view) {
                updateDispBitmapList();
                showData();
            }

            @Override
            public void onRightDismiss(View view) {
                updateDispBitmapList();
                showData();
            }

            @Override
            public void onReduction(View view) {

            }
        });
        topScaleRelativeLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Works works = new Works();
                Review review = (Review) v.getTag();
                works.setId(review.getWork_id() + "");
                Intent intent = new Intent(context, PoetryDetailAct.class);
                intent.putExtra("from", ReViewFragment.class.getSimpleName());
                intent.putExtra(Works.class.getSimpleName(), works);
                context.startActivity(intent);
            }
        });
    }

    private void updateDispBitmapList() {
        Review removeReview = showList.remove(0);
        noShowList.add(removeReview.getId() + "");
        if (noShowList.size() > 10) {
            noShowList.remove(0);
        }
    }

    // flate
    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        initView();
        initListener();
        showData();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }

    @Override
    public void OnTextTypefaceChange() {

        showData();

    }

    @Override
    public void OnTextrChange() {

        showData();

    }
}
